package com.bbz.core.Youku;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;

/**
 *设计多线程统计器。启动N个线程,线程执行时，打印每个线程执行的次数，和所有线程执行次数和
 */
public class Test_3 {
    public static void main(String args[]) {
        int sumCount = 0;
        ExecutorService executorService = Executors.newCachedThreadPool();
        //list,存放N个FutureTask
        List<FutureTask<Integer>> list = new ArrayList<>();
        //创建100个线程
        for (int i = 0; i < 10; i++) {
            FutureTask<Integer> futureTask = new FutureTask<Integer>(new Callable<Integer>() {
                //AtomicInteger保证原子性
                AtomicInteger atomicInteger = new AtomicInteger();
                @Override
                public Integer call() throws Exception {
                    //随机执行N(100以内)次
                    int count = new Random().nextInt(100) + 1;
                    for (int i = 0; i < count; i++) {
                        System.out.println(Thread.currentThread().getName() + "执行第" + atomicInteger.getAndIncrement() + "次");
                    }
                    return atomicInteger.intValue();
                }
            });
            executorService.execute(futureTask);
            list.add(futureTask);
        }
        while (true) {
            if (list.size() == 0) {
                break;
            }
            //判断List中所有的task是否完成
            for (FutureTask<Integer> task : list) {
                if (task.isDone()) {
                    try {
                        sumCount = task.get() + sumCount;
                        list.remove(task);
                        break;
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    } catch (ExecutionException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
        System.out.println("总共执行次数：" + sumCount);
        executorService.shutdown();
    }
}
